// ============================================================================
// 关键字爬取窗口管理 IPC 控制器
// ============================================================================

import { logger } from '@roasmax/logger'
import { keywordCrawlWindowService } from '../services/keyword-crawl-window-service'
import { IPCResponse } from '../../shared/types'

/**
 * 关键字爬取窗口管理控制器
 */
export class KeywordWindowController {
  
  // ============================================================================
  // IPC 方法 (推荐使用)
  // ============================================================================
  
  /**
   * 获取所有关键字窗口列表 (IPC)
   */
  async getAllWindowsIPC(): Promise<IPCResponse<any[]>> {
    try {
      logger.info('IPC: 获取所有关键字窗口列表')
      
      const windows = await keywordCrawlWindowService.getAllWindowsSummary()
      
      return {
        success: true,
        data: windows  // 直接返回窗口数组，与前端期望的 ApiResponse<KeywordWindowSummary[]> 格式匹配
      }
    } catch (error) {
      logger.error('IPC: 获取关键字窗口列表失败', { error })
      
      return {
        success: false,
        error: {
          message: error instanceof Error ? error.message : '内部服务器错误',
          code: 'INTERNAL_ERROR'
        }
      }
    }
  }
  
  /**
   * 获取特定关键字的窗口详情 (IPC)
   */
  async getKeywordWindowIPC(keyword: string): Promise<IPCResponse<any>> {
    try {
      if (!keyword || keyword.trim() === '') {
        return {
          success: false,
          error: {
            message: '关键字不能为空',
            code: 'INVALID_KEYWORD'
          }
        }
      }
      
      logger.info('IPC: 获取关键字窗口详情', { keyword })
      
      const window = await keywordCrawlWindowService.getWindowDetails(keyword)
      
      if (!window) {
        return {
          success: false,
          error: {
            message: '未找到指定关键字的窗口',
            code: 'WINDOW_NOT_FOUND'
          }
        }
      }
      
      return {
        success: true,
        data: {
          ...window.getSummary(),
          details: {
            startTime: window.startTime,
            endTime: window.endTime,
            hasMoreHistory: window.hasMoreHistory,
            lastHistoryCrawlAt: window.lastHistoryCrawlAt,
            totalPostsCrawled: window.totalPostsCrawled,
            latestPostsCrawled: window.latestPostsCrawled,
            historyPostsCrawled: window.historyPostsCrawled,
            createdAt: window.createdAt,
            updatedAt: window.updatedAt
          }
        }
      }
    } catch (error) {
      logger.error('IPC: 获取关键字窗口详情失败', { keyword, error })
      
      return {
        success: false,
        error: {
          message: error instanceof Error ? error.message : '内部服务器错误',
          code: 'INTERNAL_ERROR'
        }
      }
    }
  }
  
  /**
   * 获取关键字的搜索时间范围 (IPC)
   */
  async getKeywordTimeRangesIPC(keyword: string): Promise<IPCResponse<any>> {
    try {
      if (!keyword || keyword.trim() === '') {
        return {
          success: false,
          error: {
            message: '关键字不能为空',
            code: 'INVALID_KEYWORD'
          }
        }
      }
      
      logger.info('IPC: 获取关键字搜索时间范围', { keyword })
      
      const timeRanges = await keywordCrawlWindowService.getSearchTimeRanges(keyword)
      
      return {
        success: true,
        data: timeRanges
      }
    } catch (error) {
      logger.error('IPC: 获取关键字搜索时间范围失败', { keyword, error })
      
      return {
        success: false,
        error: {
          message: error instanceof Error ? error.message : '内部服务器错误',
          code: 'INTERNAL_ERROR'
        }
      }
    }
  }
  
  /**
   * 获取需要历史爬取的关键字列表 (IPC)
   */
  async getKeywordsNeedingHistoryCrawlIPC(interval?: number): Promise<IPCResponse<{
    keywords: string[]
    total: number
    config: {
      historyCrawlInterval: number
      historyCrawlIntervalHours: number
    }
  }>> {
    try {
      let historyCrawlInterval = 24 * 60 * 60 * 1000 // 默认24小时
      
      if (interval !== undefined) {
        if (isNaN(interval) || interval < 0) {
          return {
            success: false,
            error: {
              message: 'interval 必须是非负整数（毫秒）',
              code: 'INVALID_PARAMETER'
            }
          }
        }
        historyCrawlInterval = interval
      }
      
      logger.info('IPC: 获取需要历史爬取的关键字列表', { historyCrawlInterval })
      
      const keywords = await keywordCrawlWindowService.getKeywordsNeedingHistoryCrawl(
        historyCrawlInterval
      )
      
      logger.debug('IPC: 关键字历史爬取查询成功', {
        keywordCount: keywords.length,
        keywords: keywords.slice(0, 5), // 只记录前5个关键字
        historyCrawlInterval
      })
      
      return {
        success: true,
        data: {
          keywords,
          total: keywords.length,
          config: {
            historyCrawlInterval,
            historyCrawlIntervalHours: Math.round(historyCrawlInterval / (60 * 60 * 1000))
          }
        }
      }
    } catch (error) {
      logger.error('IPC: 获取需要历史爬取的关键字列表失败', {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
        errorType: error?.constructor?.name || 'Unknown',
        interval
      })
      
      return {
        success: false,
        error: {
          message: error instanceof Error ? error.message : '内部服务器错误',
          code: 'INTERNAL_ERROR',
          details: process.env.NODE_ENV === 'development' ? {
            stack: error instanceof Error ? error.stack : undefined,
            errorType: error?.constructor?.name || 'Unknown'
          } : undefined
        }
      }
    }
  }
  
  /**
   * 更新关键字窗口设置 (IPC)
   */
  async updateKeywordWindowIPC(keyword: string, updates: any): Promise<IPCResponse<any>> {
    try {
      if (!keyword || keyword.trim() === '') {
        return {
          success: false,
          error: {
            message: '关键字不能为空',
            code: 'INVALID_KEYWORD'
          }
        }
      }
      
      // 验证更新数据
      const validUpdates: any = {}
      
      if (updates.hasMoreHistory !== undefined) {
        if (typeof updates.hasMoreHistory !== 'boolean') {
          return {
            success: false,
            error: {
              message: 'hasMoreHistory 必须是布尔值',
              code: 'INVALID_PARAMETER'
            }
          }
        }
        validUpdates.hasMoreHistory = updates.hasMoreHistory
      }
      
      if (updates.startTime !== undefined) {
        const startTime = new Date(updates.startTime)
        if (isNaN(startTime.getTime())) {
          return {
            success: false,
            error: {
              message: 'startTime 必须是有效的日期格式',
              code: 'INVALID_PARAMETER'
            }
          }
        }
        validUpdates.startTime = startTime
      }
      
      if (updates.endTime !== undefined) {
        const endTime = new Date(updates.endTime)
        if (isNaN(endTime.getTime())) {
          return {
            success: false,
            error: {
              message: 'endTime 必须是有效的日期格式',
              code: 'INVALID_PARAMETER'
            }
          }
        }
        validUpdates.endTime = endTime
      }
      
      if (Object.keys(validUpdates).length === 0) {
        return {
          success: false,
          error: {
            message: '没有提供有效的更新参数',
            code: 'NO_VALID_UPDATES'
          }
        }
      }
      
      logger.info('IPC: 更新关键字窗口设置', { keyword, updates: validUpdates })
      
      const updatedWindow = await keywordCrawlWindowService.updateWindowSettings(
        keyword,
        validUpdates
      )
      
      return {
        success: true,
        data: updatedWindow.getSummary()
      }
    } catch (error) {
      logger.error('IPC: 更新关键字窗口设置失败', { keyword, error })
      
      return {
        success: false,
        error: {
          message: error instanceof Error ? error.message : '内部服务器错误',
          code: 'INTERNAL_ERROR'
        }
      }
    }
  }
  
  /**
   * 重置关键字窗口 (IPC)
   */
  async resetKeywordWindowIPC(keyword: string): Promise<IPCResponse<any>> {
    try {
      if (!keyword || keyword.trim() === '') {
        return {
          success: false,
          error: {
            message: '关键字不能为空',
            code: 'INVALID_KEYWORD'
          }
        }
      }
      
      logger.info('IPC: 重置关键字窗口', { keyword })
      
      const resetWindow = await keywordCrawlWindowService.resetWindow(keyword)
      
      return {
        success: true,
        data: resetWindow.getSummary()
      }
    } catch (error) {
      logger.error('IPC: 重置关键字窗口失败', { keyword, error })
      
      return {
        success: false,
        error: {
          message: error instanceof Error ? error.message : '内部服务器错误',
          code: 'INTERNAL_ERROR'
        }
      }
    }
  }
  
  /**
   * 删除关键字窗口 (IPC)
   */
  async deleteKeywordWindowIPC(keyword: string): Promise<IPCResponse<void>> {
    try {
      if (!keyword || keyword.trim() === '') {
        return {
          success: false,
          error: {
            message: '关键字不能为空',
            code: 'INVALID_KEYWORD'
          }
        }
      }
      
      // 检查窗口是否存在
      const existingWindow = await keywordCrawlWindowService.getWindowDetails(keyword)
      if (!existingWindow) {
        return {
          success: false,
          error: {
            message: '未找到指定关键字的窗口',
            code: 'WINDOW_NOT_FOUND'
          }
        }
      }
      
      logger.info('IPC: 删除关键字窗口', { keyword })
      
      await keywordCrawlWindowService.deleteWindow(keyword)
      
      return {
        success: true
      }
    } catch (error) {
      logger.error('IPC: 删除关键字窗口失败', { keyword, error })
      
      return {
        success: false,
        error: {
          message: error instanceof Error ? error.message : '内部服务器错误',
          code: 'INTERNAL_ERROR'
        }
      }
    }
  }
}

export const keywordWindowController = new KeywordWindowController()
